$(function(){
//	var pageIndexInput = $("#pageIndexInput");
	var zoomSelectSlider = $("#zoomSelectSlider");
	var btnActiveClass = "fwr-active-btn";
	var btnDisabledClass = "disabled";
	var btnSearchDel = $("#search .icon");
	var btnZoomOut = $(".btnZoomOut");
	var btnZoomIn = $(".btnZoomIn");
	var selectZoom = $(".btnSelectZoom");
	var btnGoToFirstPage = $("#btnGoToFirstPage");
	var btnGoToPreviousPage = $("#btnGoToPreviousPage");
	var btnGoToNextPage = $("#btnGoToNextPage");
	var btnGoToLastPage = $("#btnGoToLastPage");  
	var pageIndexInputSelect = $("#pageIndexInputSelect");      
	var btnHandTool = $(".btnHandTool");
	var btnTextSelectTool = $(".btnTextSelectTool");
	var btnSelectAnnotation = $(".btnSelectAnnotation");
	var btnTypewriter = $("#btnTypewriter");
	var btnNote = $("#btnNote");
	var btnHighlight = $("#btnHighlight");
	var searchPreviousBtn = $("#search .search-previous-btn");
	var searchNextBtn = $("#search .search-next-btn");
	var textSearchInput = $("#search input");
	
	
	/******************************************Find*********************************************/
	function _getSearchText() {
	    return textSearchInput.val().replace(/(^\s*)|(\s*$)/g, "");  
	}
	function _searchText(direction){
		WebPDF.ViewerInstance && WebPDF.ViewerInstance.searchText(_getSearchText(), direction);
    };
    function _updateSearchBtnState() {
        var txtSearch = _getSearchText();
        var bEnable = !!txtSearch;
        if (bEnable){         
            $("#search .icon").removeClass("search-icon").addClass("search-clear-btn");
            searchPreviousBtn.removeClass("disabled");
            searchNextBtn.removeClass("disabled");
        }
        else{
            $("#search .icon").addClass("search-icon").removeClass("search-clear-btn");
            searchPreviousBtn.addClass("disabled");
            searchNextBtn.addClass("disabled");
        }   
    };
    searchPreviousBtn.click(function(event){
        _searchText(WebPDF.SearchDirection.Up);
        event.stopPropagation();
    });
    searchNextBtn.click(function(event){           
        _searchText(WebPDF.SearchDirection.Down);
         event.stopPropagation();
    });
    textSearchInput.on("click", function () {
        textSearchInput.focus();            
        return true;
    }).on("keyup", function (d) {
        if(d.keyCode == "13" || d.keyCode == "40"){
            _searchText(WebPDF.SearchDirection.Down);               
        }
        if(d.keyCode == "38"){
        	_searchText(WebPDF.SearchDirection.Up);
        }
        return true;
    });
    btnSearchDel.click(function(event){
    	textSearchInput.val("");
        _updateSearchBtnState();
        event.stopPropagation();
    });
    $(".fwr-mainframe-header").click(function(){
        $("#search").hide();
        $("#find").show();
        $("#search > input").css("width", "0px").val("");
    });
       
    $("#search, #find").click(function(event){
       event.stopPropagation();
    });
    $("#find").click(function(){	   
	    $("#find").hide();
	    $("#search").show();
	    $("#query").animate({width:"200px"});
	    $("#query").focus();
	});


    /******************************************View*********************************************/
    $(".btn-actual-size").on("click", function(){
    	if (WebPDF.ViewerInstance) {
    		WebPDF.ViewerInstance.zoom(WebPDF.ZOOM_ACTUAL_SIZE);
        	$(this).addClass("actualsize24");
        	$(".btn-fit-width").removeClass("fitwidth16");
        	$(".btn-fit-page").removeClass("fitpages");
    	}
    });
	$(".btn-fit-page").on("click", function () {
    	if (WebPDF.ViewerInstance) {
    		WebPDF.ViewerInstance.zoom(WebPDF.ZOOM_FIT_PAGE);
        	$(this).addClass("fitpages");
        	$(".btn-actual-size").removeClass("actualsize24");
        	$(".btn-fit-width").removeClass("fitwidth16");
		}
    });
	$(".btn-fit-width").on("click", function () {
    	if (WebPDF.ViewerInstance) {
    		WebPDF.ViewerInstance.zoom(WebPDF.ZOOM_FIT_WIDTH);
        	$(this).addClass("fitwidth16");
        	$(".btn-actual-size").removeClass("actualsize24");
        	$(".btn-fit-page").removeClass("fitpages");
    	}
    });
/*	$(".btn-fit-visible").click(function(){
		WebPDF.ViewerInstance && WebPDF.ViewerInstance.zoom(WebPDF.ZOOM_FIT_VISIBLE);
	});*/
    btnZoomOut.on("click", function () {
    	WebPDF.ViewerInstance && WebPDF.ViewerInstance.zoom(WebPDF.ZOOM_OUT);
    });
    btnZoomIn.on("click", function () {
    	WebPDF.ViewerInstance && WebPDF.ViewerInstance.zoom(WebPDF.ZOOM_IN);
    });
    selectZoom.on("change", function () {
    	if (WebPDF.ViewerInstance) {
	    	var zoomVal = $(this).val();
	        var val = parseFloat(zoomVal);
	        if(val){
	        	zoomVal = val / 100;
	        }
	        WebPDF.ViewerInstance.zoom(zoomVal);
    	}
    });
    
    /******************************************StatusBar*********************************************/
    pageIndexInputSelect.change(function(){
        var selectPage = pageIndexInputSelect.val();
        WebPDF.ViewerInstance.goToPage(parseInt(selectPage));
    });
    btnGoToFirstPage.on("click", function () {
		WebPDF.ViewerInstance && WebPDF.ViewerInstance.goToPage(0);
    });
    btnGoToPreviousPage.on("click", function () {
    	WebPDF.ViewerInstance && WebPDF.ViewerInstance.goToPrevPage();
    });
    btnGoToNextPage.on("click", function () {
    	WebPDF.ViewerInstance && WebPDF.ViewerInstance.goToNextPage();
    });
    btnGoToLastPage.on("click", function () {
    	WebPDF.ViewerInstance && WebPDF.ViewerInstance.goToPage(WebPDF.ViewerInstance.getPageCount() - 1);
    });
/*    
    pageIndexInput.on("click", function () {
        this.focus();
        return true;
    }).on("keypress", function (d) {
        if (d.keyCode == "13") { //enter
            var value = $(this).val();
            (value < 1 || isNaN(value)) && pageIndexInput.val(1);
            WebPDF.ViewerInstance && WebPDF.ViewerInstance.goToPage(parseInt(pageIndexInput.val() - 1));
        }
        return true;
    });
 */
    
    /******************************************Tool*********************************************/
    btnHandTool.on("click", function () {
    	WebPDF.ViewerInstance && WebPDF.ViewerInstance.setCurrentToolByName(WebPDF.Tools.TOOL_NAME_HAND);
    });
    btnTextSelectTool.on("click", function () {
    	WebPDF.ViewerInstance && WebPDF.ViewerInstance.setCurrentToolByName(WebPDF.Tools.TOOL_NAME_SELECTTEXT);
    });
    btnSelectAnnotation.on("click", function () {
    	WebPDF.ViewerInstance && WebPDF.ViewerInstance.setCurrentToolByName(WebPDF.Tools.TOOL_NAME_SELANNOT);
    });
    
    /******************************************Annot*********************************************/
    btnTypewriter.on('click',function(){
		WebPDF.ViewerInstance && WebPDF.ViewerInstance.setCurrentToolByName(WebPDF.PDFData.TypewriterAnnotType.TYPEWRITERTYPE_TYPEWRITER);
	});
    btnNote.on('click',function(){
		WebPDF.ViewerInstance && WebPDF.ViewerInstance.setCurrentToolByName(WebPDF.Tools.TOOL_NAME_TEXTANNOT);
	});
    $("#btnHighlight").on('click',function(){
		WebPDF.ViewerInstance && WebPDF.ViewerInstance.setCurrentToolByName(WebPDF.PDFData.CommentAnnotType.COMMENTTYPE_HIGHLIGHT);
	});
    
    $("#btnUnderline").on('click',function(){
    	WebPDF.ViewerInstance && WebPDF.ViewerInstance.setCurrentToolByName(WebPDF.PDFData.CommentAnnotType.COMMENTTYPE_UNDERLINE);
	});
	/*$("#btnStrikeout").on('click',function(){
		WebPDF.ViewerInstance && WebPDF.ViewerInstance.setCurrentToolByName(WebPDF.PDFData.CommentAnnotType.COMMENTTYPE_STRIKEOUT);
	});*/
	
	$("#btnPencel").on('click', function(){	
		WebPDF.ViewerInstance && WebPDF.ViewerInstance.setCurrentToolByName(WebPDF.Tools.TOOL_NAME_INKANNOT);
	});
	
	/******************************************Form*********************************************/
	$(".highlight-fields").on("click", function(){
    	if (WebPDF.ViewerInstance) {
	    	var formPlugin = WebPDF.ViewerInstance.getPluginByName(WebPDF.FormPluginName);
	    	if (formPlugin) {
	    		formPlugin.toggleHighlight();
	    	}
    	}
    });
    $(".reset-form").on("click", function(){     
    	if (WebPDF.ViewerInstance) {
	    	var confirmBody = $("<div>").append("<div class='icon'><img src='./image/disable.png'/></div><div class='msg'></div>");
	        confirmBody.find(".msg").append('<span>This option will reset all form to their default values.You may lose some data. Are you sure?</span>');
	 
	        confirmBody.find(".icon").css({width: "30px", height:"30px", float: "left"});     
	        confirmBody.find(".msg").css({width: "380px", float: "right"});      
	        WebPDF.confirm(WebPDF.ViewerInstance.getApp(), "Reset Form", confirmBody.prop('outerHTML'), "Yes", "No", function(isOk){
	        	var formPlugin = WebPDF.ViewerInstance.getPluginByName(WebPDF.FormPluginName);
	        	if (isOk && formPlugin) {
	        		formPlugin.resetForm();
	        	}
	        }, '450px', '45px');
    	}
    });
    
    /******************************************Signature*********************************************/
    /*$("#signatureCreateModal").on("click", function () {
		$(this).addClass("createsign24");
	});
    $("#getSignatureList").on("click", function () {
		 $(this).addClass("sign24");
		 $(".createsign").removeClass("createsign24");
    });*/
    
	
	/******************************************Login/Logout*********************************************/
	$("#btn-signin-up").click(function(){
 		$("#promptinfo").text("");
 	});
 	$(".close").click(function(){
 		$('#myModal-dialog').modal('hide');
 		$('#myModal-account').modal('hide');
 	});
 	$("#btn-signin-drop").click(function(){
 		$('#myModal-dialog').modal('show');
 		$("#signup-div").css("display","none");
 		$("#signin-div").css("display","block");
 	});
 	
 	$(window).load(function(){
 		if(window.email){
 			$("#btn-signin-drop").css("display","none");
			$("#div-signin").css("display","block");
			$("#btn-sign-dropdown").text(window.email);
			$("#useraccount").html(window.email);
			WebPDF.loginEmail = window.email;
 		}
 	});
 	$("#btn-signin").click(function(){
 		var username = $("#username").val();
 		var password = $("#password").val();
 		$.ajax({
			url:"./login",
			type:"POST",
			dataType: 'json',
			data:{"username":username,"password":password},
			success: function(result){
				if(result.success){
					$("#btn-signin-drop").css("display","none");
					$('#myModal-dialog').modal('hide');
					$("#div-signin").css("display","block");
					$("#btn-sign-dropdown").text(result.email);
					$("#useraccount").html(result.email);
					WebPDF.loginEmail = result.email;
				}else{
					$("#promptinfo").text(result.msg);
					$("#promptinfo").addClass("alert");
					$("#promptinfo").addClass("alert-danger");
					$("#username").val("");
					$("#password").val("");
					WebPDF.loginEmail = "";
				}
	        },
	        error:function(XMLHttpRequest, textStatus, errorThrown){
	        	WebPDF.loginEmail = "";
	        }
 		});
 	});
 	$("#li-myaccount").click(function(){
 		$('#myModal-account').modal('show');
 		$("#div-account").css("display","block");
 	});
 	$("#a-signup").click(function(){
 		$("#signin-div").css("display","none");
 		$("#signup-div").css("display","block");
 	});
 	$("#btn-myprofile").click(function(){
 		$.ajax({
 			url:"./updateprofile",
 			type:'post',
 			dataType: 'json',
 			data:{"firstname":$("#firstname").val(),"lastname":$("#lastname").val()},
 			success:function(result){
 				if(result.success){
 					$("#firstname").val("");
 					$("#firstname").val("");
 					$("#span-myprofile").html("Update profile successed.");
 				}else{
 					$("#span-myprofile").html("Update profile failed.");
 				}
 			},
 			error:function(result){
 				$("#span-myprofile").html("Update profile failed.");
 			}
 		});
 	});
 	$("#btn-signup").click(function(){
 		var email = $("#signup-username").val();
 		if(email.indexOf('@') == -1){
 			return;
 		}
 		
 		$.ajax({
 			url:"./register",
 			type:'post',
 			dataType:'json',
 			data:{"email":email},
 			success:function(result){
 				if(result.success){
 					
 				}else{
 					$("#span-signup").html(result.msg);
 					$("#signup-username").val("");
 				}
 			},
 			error:function(){
 				
 			}
 		});
 	});
 	$("#btn-security").click(function(){
 		var newpas = $("#newpassword").val();
 		var newconfpas = $("#confirmpassword").val();
 		
 		if(newpas != newconfpas){
 			$("#span-mysecurity").html("The passwords you entered do not match.Enter the same password in both boxes.");
 			return;
 		}
 		$.ajax({
 			url:"./updatepassword",
 			type:'post',
 			dataType:'json',
 			data:{"currentpassword":$("#currpassword").val(),"newpassword":newpas},
 			success:function(result){
 				if(result.success){
 					$("#newpassword").val("");
 					$("#currpassword").val("");
 					$("#confirmpassword").val("");
 					$("#span-mysecurity").html("Update password successed.");
 				}else{
 					$("#span-mysecurity").html("Update password failed.");
 				}
 			},
 			error:function(result){
 				$("#span-mysecurity").html("Update password failed.");
 			}
 		});
 	});
 	$("#li-signout").click(function(){
 		$.ajax({
 			url:"./logout",
 			type:'post',
 			dataType:'json',
 			success:function(result){
 				if(result.success){
 					$("#btn-signin-drop").css("display","block");
					$('#myModal-dialog').modal('hide');
					$("#div-signin").css("display","none");
					$("#btn-sign-dropdown").html(result.email);
					$("#useraccount").html(result.email);
					WebPDF.loginEmail = "";
 				}else{
 					
 				}
 			},
 			error:function(){
 				alert("error");
 			}
 		});
 	});
 	
	/******************************************FullScreen other*********************************************/
	$("#up-down").click(function(){
		var heightmp = $("#div-opt-tab-content").height() + $("#tab-list").height();
		$("#div-opt-tab-content,#tab-list").slideToggle("slow",function(){
			if($("#div-opt-tab-content").is(":hidden")){
				$("#up-down").removeClass().addClass("down li16");
				$(".fwr-doc-viewer,#docViewer_ViewContainer,.fwrJspContainer").height($(".fwr-doc-viewer").height() + heightmp);
			}else{
				$("#up-down").removeClass().addClass("up li16");
			}
		});
	});

	$("#btnFullScreen").click(function (e) {
	    if (!$.support.fullscreen) {//不支持全屏
	        //WebPDF.alert(viewerInstance.getApp(),null,i18n.t("CommandUI.FullScreenUnSupport"));
	    	alert('Your browser does not supports full screen');
	        return;
	    }

	    $("#Viewer").fullScreen({
	        'callback': function (isFullScreen) {
	            if (!isFullScreen) {
	                //window.onresize();
	            	$("#btnFullScreen").removeClass().addClass("fullview li16");
	            }
	            else {
	                //window.onresize();
	            	$("#btnFullScreen").removeClass().addClass("esc_nor li16");
	            }
	        }
	    });
	});
	
	$(window).bind('beforeunload',function(){
		if(WebPDF.ViewerInstance.getDocView().isModified()){
				return 'You have made changes to your documents that have not been saved. Are you sure want to discard them?';
		}else{
			$(window).unbind('beforeunload');
		}
	});
	

	//File
	 $(document).on("click","#navbarDrop1",function(){
	   	$(this).addClass("open24");
		$("#FileSave").removeClass("save24");
		$("#FileSaveas").removeClass("saveas24");
	 });
	 $(document).on("click","#FileSave",function(){
	   	$(this).addClass("save24");
		$("#FileSaveas").removeClass("saveas24");
		$("#navbarDrop1").removeClass("open24");
	 });
	 $(document).on("click","#FileSaveas",function(){
		 $(this).addClass("saveas24");
		 $("#FileSave").removeClass("save24");
		 $("#navbarDrop1").removeClass("open24");
	 });
	
    
	/******************************************事件绑定*********************************************/
	/*Capture the window resize event to adjust UI of Reader.*/
    $(window).resize(function(){
        if (WebPDF && WebPDF.ViewerInstance) {
        	var mainFrameWidth = $(this).width();
            var mainFrameHeight = $(this).height();
            var headerControl = $("#headerControl");
            var statusBar = $("#bottomControl");
            var isHeaderHide = headerControl.is(":hidden");
            var isStatusBarHide = statusBar.is(":hidden");
            var headerHeight = isHeaderHide ? 0 : headerControl.outerHeight();
            var statusBarHeight = isStatusBarHide ? 0 : statusBar.outerHeight();
            var  viewerHeight = mainFrameHeight - headerHeight - statusBarHeight;
            
            $(".fwr-doc-viewer").css({               
                height: viewerHeight
            });            
           // WebPDF.ViewerInstance.updateLayout(mainFrameWidth, viewerHeight);
        }
    });
	//绑定AppInstance事件
	function _bindEventsForAppInstance() {  
	     if (!WebPDF.ViewerInstance) {
	         return true;
	     }    
	     
       
	     WebPDF.ViewerInstance.on(WebPDF.EventList.TOOL_CHANGED, function (event, data) {
	     	_updateToolsUI(data.oldToolName, data.newToolName);
	     }).on(WebPDF.EventList.DOCVIEW_ZOOM_CHANGED, function (event, data) {        
	         var zoomMode = WebPDF.ViewerInstance.curZoomMode();        
	         if (zoomMode == WebPDF.ZOOM_FIT_WIDTH){
	             $(".fit-width").addClass(btnActiveClass);         
	         }
	         else{
	             $(".fit-width").removeClass(btnActiveClass);
	         }
	         
	         WebPDF.ViewerInstance.canZoomIn() ? btnZoomIn.removeClass(btnDisabledClass) : btnZoomIn.addClass(btnDisabledClass);
	         WebPDF.ViewerInstance.canZoomOut() ? btnZoomOut.removeClass(btnDisabledClass) : btnZoomOut.addClass(btnDisabledClass);      
	       
	        
	         if (zoomMode == WebPDF.ZOOM_NUMBER){
	             selectZoom.val(data.newScale * 100);        
	         }    
	         else{
	             selectZoom.val(zoomMode);        
	         }
	         
	         var currentZoomIndex = -1;  
	         var zoomList = WebPDF.ViewerInstance.getCurrentScaleList();
	         for (var i = 0; i < zoomList.length; i++) {
	             var zoom = zoomList[i];
	             if (zoom == data.newScale) {
	                 currentZoomIndex = i;
	                 break;
	             }
	         }       
	         zoomSelectSlider.slider('value', currentZoomIndex);        
	     }).on(WebPDF.EventList.DOCVIEW_PAGE_CHANGED, function (event, data) {
	         var bFirstPage = data.curIndex === 0;
	         var bLastPage = data.curIndex === WebPDF.ViewerInstance.getPageCount() - 1;
	         if (bFirstPage) {
	             btnGoToFirstPage.addClass(btnDisabledClass);
	             btnGoToPreviousPage.addClass(btnDisabledClass);
	         }
	         else {
	             btnGoToFirstPage.removeClass(btnDisabledClass);
	             btnGoToPreviousPage.removeClass(btnDisabledClass);
	         }
	         if (bLastPage) {
	             btnGoToNextPage.addClass(btnDisabledClass);
	             btnGoToLastPage.addClass(btnDisabledClass);
	         }
	         else {
	             btnGoToNextPage.removeClass(btnDisabledClass);
	             btnGoToLastPage.removeClass(btnDisabledClass);
	         }
//	         pageIndexInput.length>0 && pageIndexInput.val(data.curIndex + 1);
	         pageIndexInputSelect.length>0 && pageIndexInputSelect.val(data.curIndex);
	     }).on(WebPDF.EventList.DOCUMENT_LOADED, function (event, data) {       
	         $(".group-tools").removeClass("disabeld");
	         $(".group-view").removeClass("disabled");
	         $(".group-tool").removeClass("disabled");
	         $(".group-tools").removeClass("disabled");
	         $(".group-share").removeClass("disabled");
	         $(".group-save").removeClass("disabled");
	         $(".group-views").removeClass("disabled");
	         $(".group-comment").removeClass("disabled");
	         $(".group-drawing").removeClass("disabled");
	         $(".group-formData").removeClass("disabled");
	         $(".group-sign").removeClass("disabled");
	         $(".operation-share").removeClass("disabled");
	         _loadUIForAppInstance();
	         $("#span-filename").html(WebPDF.ViewerInstance.getFileName());
	     }).on(WebPDF.EventList.DOC_MODIFY_STATE_CHANGED, function(event, isModified){                     
	         if (isModified){
	             $(".operation-save").removeClass("disabled");
	             $(".operation-saveas").removeClass("disabled");
				 $(".operation-save-group").removeClass("disabled");
	         }else{
	         	$(".operation-save").addClass("disabled");
	         	$(".operation-saveas").addClass("disabled");
				$(".operation-save-group").addClass("disabled");
	         }
	     }).on("NotFound", function(){
	         searchPreviousBtn.addClass(btnDisabledClass);
	         searchNextBtn.addClass(btnDisabledClass);
	      });
	     
	     //IE
	     if (WebPDF.Environment.ie) {
	     	textSearchInput.get(0).attachEvent("onpropertychange", function (o) {
	     		_updateSearchBtnState();
	     	});    
	     } else {//非IE
	     	textSearchInput.on('input', function (o) {	                  
	     		_updateSearchBtnState();
	     	});
	     }
	     
	     zoomSelectSlider.slider({
	         range: "max",
	         min: 0,
	         max: WebPDF.Config.defaults.zoomList.length+1,
	         value: 0,
	         slide: function (event, ui) {
	         	if (WebPDF.ViewerInstance) {
	         		var zoomList = WebPDF.ViewerInstance.getCurrentScaleList();              
	                 var zoomSelected = zoomList[ui.value];             
	                 WebPDF.ViewerInstance.zoom(zoomSelected);
	         	}
	         }
	     });	 		 	
	 	
	 }
	 function _loadUIForAppInstance() {  
			pageIndexInputSelect.empty();
		    if(pageIndexInputSelect.length > 0){
		        var pageCnt = WebPDF.ViewerInstance.getPageCount();
		        for(var i=0; i<pageCnt; i++){
		            pageIndexInputSelect.append("<option value='" + i + "'>" + (i+1) + " / " +  pageCnt +"</option>");
		        }
		    }
		    
		    selectZoom.empty();
		    var zoomList = WebPDF.ViewerInstance.getAvailableZoomList();
		    for (var i = 0; i < zoomList.length; i++){
		        var obj = zoomList[i];     
		        var option = $("<option>").val(obj.key).html(obj.value);
		        selectZoom.append(option);
		    }
		          
		    var curZoom = WebPDF.ViewerInstance.getCurZoom();  
		    var zoomMode = WebPDF.ViewerInstance.curZoomMode();
		    if (zoomMode == WebPDF.ZOOM_NUMBER){
		        selectZoom.val(data.curZoom * 100);        
		    } else {
		        selectZoom.val(zoomMode);        
		    }
		        
		    var currentZoomIndex = -1;
		    var zoomList = WebPDF.ViewerInstance.getCurrentScaleList();
		    for (var i = 0; i < zoomList.length; i++) {
		        var zoom = zoomList[i];
		        if (zoom == curZoom) {
		            currentZoomIndex = i;
		            break;
		        }
		    }
		    zoomSelectSlider.slider('value', currentZoomIndex);
		    _updateToolsUI(null,WebPDF.ViewerInstance.getCurToolHandler().getName());
	}
	 //处理更新工具条更改时样式处理
	function _updateToolsUI(oldToolName, newToolName) {
		$(".webpdftool").removeClass("hover");
		if (newToolName === WebPDF.Tools.TOOL_NAME_HAND) {
			btnHandTool.addClass("hover");
		} else if (newToolName === WebPDF.Tools.TOOL_NAME_SELECTTEXT) {
			btnTextSelectTool.addClass("hover");
		} else if (newToolName === WebPDF.Tools.TOOL_NAME_SELANNOT) {
			btnSelectAnnotation.addClass("hover");
		 } else if (newToolName === WebPDF.PDFData.TypewriterAnnotType.TYPEWRITERTYPE_TYPEWRITER) {		
			 btnTypewriter.addClass("hover");
		 } else if (newToolName === WebPDF.Tools.TOOL_NAME_TEXTANNOT) {
			 btnNote.addClass("hover");
		 } else if (newToolName === WebPDF.PDFData.CommentAnnotType.COMMENTTYPE_HIGHLIGHT) {
			 btnHighlight.addClass("hover");
		 } else if (newToolName === WebPDF.PDFData.CommentAnnotType.COMMENTTYPE_UNDERLINE) {
			 $("#btnUnderline").addClass("hover");
		} else if (newToolName === WebPDF.Tools.TOOL_NAME_INKANNOT) {
			 $("#btnPencel").addClass("hover"); 
		} else if (newToolName === WebPDF.Tools.TOOL_NAME_SIGNATURE) {
			var signaturePlugin = WebPDF.ViewerInstance.getPluginByName(WebPDF.SignaturePluginName);
			var curSingnature = signaturePlugin.getCurSingnature();
			var id = curSingnature ? curSingnature.getId() : "";
			if (id == WebPDF.PDFData.BaseSignature.Text) {
				$("#textSignature").addClass("hover"); 
			} else if (id == WebPDF.PDFData.BaseSignature.Date){
				$("#dateSignature").addClass("hover"); 
			}
		}
	}
	var _formPluginModule = null;
	function _createPDFView(assertUrl) {
        var docParent = $(".fwr-doc-viewer").empty();     	
        docParent.append('<div id="docViewer" style="position:relative; height:100%"></div>');		
		//curView.registerPlugin(_formPluginModule);       
        
        var options = {              
	        language: "en-US",
	        formMode: true,
			defaultZoom: WebPDF.ZOOM_FIT_WIDTH,
	        leftPanelShowOnStart: false,
	        scrollBarType: 1,
	        crossDomain: false,
	        url: assertUrl,
            fileId : "doc-1",
            url: "/rest/webpdf/",
            baseUrl: "/",
            defaultDialogTitle:'Forms Publisher',
            userName :  "userName"            
		};
                
        WebPDF.createView("docViewer", options, function(curView){
            curView.addIgnoreMouseEventClass("fwr-search-ui-area");
	       _bindEventsForAppInstance();
        })		
	};  
    
    _createPDFView("doc-1");
	
	
	var height = $(window).height() - $("#headerControl").outerHeight() - $("#bottomControl").outerHeight();
	$(".fwr-doc-viewer").css("height", height);
	
	
	//*******************************document list javascript********************************************************

	var _fromcloudClass = "fromCloud";
	var _docListModal = "docListModal";
	var _docList = "docList";
	var _sortDocList = "sortDocList";
	var _findFile = "findFile";
	var _seachSapn = "seachSapn";
	
	var _docListData = "";
	
	var _getDocListUrl = "./getDocList";
	var _getDocumentAssertUrl = "./getDocAssertUrl"
	
    var _seachColor = "red";
	var _getDocListError = "get document list error";
	var _getDocumentAssertUrlError = "get document assert url error";
	//未登录提示语
	var _notLoginInfo = "Please login and operation"
	$(document).on("click","."+_fromcloudClass,function(){
		$("#"+_docListModal).modal("show")
		//先注释掉登录验证
		/*checkLogin(function(){
			$("#"+_docListModal).modal("show")
		});*/
	})
	
	
	$(document).on("shown.bs.modal","#"+_docListModal,function(){
		$.ajax({
			url:_getDocListUrl,
			type:"GET",
			dataType: 'json',
			contentType:'application/x-www-form-urlencoded',
			success: function(data){
				if(data.ret == 0){
					_docListData = data.list;
					//重大到小排序
					docListSort(_docListData,"floor");
					docListHtml(_docListData)
				}else{
					alert(_getDocListError);
				}
			},
			error:function(){
				alert(_getDocListError);
			}
	    }); 
	});
	
	
	$(document).on("click","#"+_docList+" tbody tr",function(){
		var docId = $(this).attr("docId");
		var getDocumentAssertUrl = _getDocumentAssertUrl + "/"+docId;
		$.ajax({
			url:getDocumentAssertUrl,
			type:"Get",
			dataType: 'json',
			contentType:'application/x-www-form-urlencoded',
			success: function(data){
				if(data.error == 0){
					$("#"+_docListModal).modal("hide")
					_createPDFView(data.urls.asserts);
				}else{
					alert(_getDocumentAssertUrlError);
				}
			},
			error:function(){
				alert(_getDocumentAssertUrlError);
			}
	    });
	})
	
	//排序
	$(document).on("click","#"+_sortDocList,function(){
		var sort = $(this).attr("sort");
		if(sort == "floor"){
			sort = "ceil";
		}else if(sort == "ceil"){
			sort = "floor";
		}
		docListSort(_docListData,sort);
		docListHtml(_docListData)
	});
	
	$(document).on("click","#"+_seachSapn,function(){
		$(this).find("span").hide();
		$("#"+_findFile).show().focus();
	});
	
	//搜索文档
	$(document).on("keyup","#"+_findFile,function(){
		var seachInfo = $(this).val();
		//特殊字符没有处理
		//seachInfo.replaceAll("\\.",".").replaceAll("\\&","").replaceAll("","")
		var replaceText = "<font style='color:" + _seachColor + ";'>"+seachInfo+"</font>"; 
		$("#"+_docList+" tbody tr").each(function(){
			var object = $(this).find("td:first");
			var fileName = object.text();
			fileName = fileName.replaceAll(seachInfo,replaceText);
			object.html(fileName);
		});
	});
	
	String.prototype.replaceAll = function replaceAll(s1,s2){
		return this.replace(new RegExp(s1,"g"),s2);
	}
	
	//sort:floor 重大到小 , ceil 重小到大
	function docListSort(docList,sort){
		$("#"+_sortDocList).attr("sort",sort);
		for(var i = 0; i < docList.length; i++){
			for(var j = i+1; j < docList.length;j++){
				var docObj = docList[i]
				var docObjOther = docList[j];
				var modifiedDate = docObj.mtime;
				var modifiedDateOther = docObjOther.mtime;
				if(sort == "floor"){
					if(modifiedDate < modifiedDateOther){
						var temp = docList[i];
						docList[i] = docObjOther;
						docList[j] = temp;
					}
				}else if(sort == "ceil"){
					if(modifiedDate > modifiedDateOther){
						var temp = docList[i];
						docList[i] = docObjOther;
						docList[j] = temp;
					}
				}
			}
		}
	}
	
	function docListHtml(docList){
		var html = "";
		for(var i = 0; i < docList.length; i++){
			var docObj = docList[i]
			var fileName = docObj.path;
			fileName = fileName.substr(1,fileName.length);
			var size = Math.round(docObj.size/1024) + "KB";
			var modifiedDate = docObj.mtime;
			modifiedDate = new Date(modifiedDate).format("yyyy-MM-dd hh:mm");
			var docId = docObj.doc_id;
			
			html += "<tr docId="+docId+"><td style=\"border:0px\">"+fileName+"</td>"
			html += "<td style=\"border:0px\">"+size+"</td>"	
			html += "<td style=\"border:0px\">"+modifiedDate+"</td></tr>"	
		}
		$("#"+_docList+" tbody").html(html);
	}
	
	
	Date.prototype.format =function(format)
	{
		var o = {
			"M+" : this.getMonth()+1, //month
			"d+" : this.getDate(), //day
			"h+" : this.getHours(), //hour
			"m+" : this.getMinutes(), //minute
			"s+" : this.getSeconds(), //second
			"q+" : Math.floor((this.getMonth()+3)/3), //quarter
			"S" : this.getMilliseconds() //millisecond
		}
		if(/(y+)/.test(format)) format=format.replace(RegExp.$1,
		(this.getFullYear()+"").substr(4- RegExp.$1.length));
		for(var k in o)if(new RegExp("("+ k +")").test(format))
		format = format.replace(RegExp.$1,
		RegExp.$1.length==1? o[k] :
		("00"+ o[k]).substr((""+ o[k]).length));
		return format;
	}
});